import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import nProgress from 'nprogress'

//  axios 二次封装
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // console.log(config)
    nProgress.start()
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  (error) => {
    nProgress.done()
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    nProgress.done()

    const res = response.data
    if (res.code !== 200 && res.code !== 20000) {
      // return Promise.reject(new Error(res.message || 'Error'))
      res.ok = false
      return res
    } else {
      // if (Array.isArray(res.data)) {
      //   res.data = res.data.reverse()
      // }

      if (res.data && res.data.records)
        if (Array.isArray(res.data.records)) {
          res.data.records = res.data.records.reverse()
        }
      res.ok = true
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })

    nProgress.done()
    return Promise.reject(error)
  }
)

export default service
